import Tool from "../../lib/common/Tool";
import MsgMgr from "../../lib/event/MsgMgr";

class MsgResult {
    public id:number;
    public ret:number;
    public data:any;
}

export default class Http {
    private _session:string;//会话id
    public set session(val:string) {
        this._session = val;
    }
    public get session():string {
        return this._session;
    }

    private static _errorHandler:any;
    public static set errorHandler(val) {
        Http._errorHandler = val;
    }
    public static get errorHandler() {
        return Http._errorHandler;
    }

    private _url:string;
    public set url(val:string) {
        this._url = val;
    }
    public get url():string {
        return this._url;
    }

    private _retryNum:number = 5;//重试次数

    private cache = [];

    private fillMsgData(msgId, params) {

        if (msgId == 10000) {
            return params;
        }

        let msg:any = {};
        msg.msgHead = {"id":msgId,"gameSessionKey":this.session};
        msg.data = {};
        if(params)
        {
            for(var key in params)
            {
                msg.data[key] = params[key];
            }
        }
        return msg;
    }

    private cacheCallInfo(id, callback) {
        let realid = Tool.msgRealId(id);
        if (!this.cache[realid]) {
            this.cache[realid] = [callback];
        } else if (this.cache[realid].indexOf(callback) == -1) {
            this.cache[realid].push(callback);
        }
    }

    public send(id, param, callback, count = 0) {
        this.cacheCallInfo(id, callback);//存储回调信息
        const msg = this.fillMsgData(id, param);
        let xhr = cc.loader.getXMLHttpRequest();
        var data:string = JSON.stringify(msg);//encodeURI(JSON.stringify(msg));
        xhr.open("GET", this.url + "?data="+data, true);
        xhr.onreadystatechange = function () {
            this.handler(xhr);
        }.bind(this);
        xhr.onerror = function (err) {
            this.onGetError(id, param, callback, count+1, err);
        }.bind(this);
        xhr.ontimeout = function (timeout) {
            this.onGetTimeout(id, param, callback, count+1, timeout);
        }.bind(this);
        try {
            xhr.send();
        } catch (error) {
            console.error(error)         
        }
    }

    public post(id, param, callback, count = 0) {
        this.cacheCallInfo(id, callback);//存储回调信息
        const msg = this.fillMsgData(id, param);
        var data:string = JSON.stringify(msg);//encodeURI(JSON.stringify(msg));
        let xhr = cc.loader.getXMLHttpRequest();
        -
        xhr.open("POST", this.url, true);
        xhr.setRequestHeader("Content-type","application/json");
        //xhr.setRequestHeader("Authorization", "Bearer "+this.session);
        
        xhr.send(data);
        xhr.onreadystatechange = function () {
            this.handler(xhr);
        }.bind(this);
        xhr.onerror = function (err) {
            this.onPostError(id, param, callback, count+1, err);
        }.bind(this);
        xhr.ontimeout = function (timeout) {
            this.onPostTimeout(id, param, callback, count+1, timeout);
        }.bind(this);
    }

    private onGetError(id, param, callback, count, err) {
        if (count < this._retryNum) {
            this.send(id, param, callback, count);
        }
    }

    private onGetTimeout(id, param, callback, count, timeout) {
        if (count < this._retryNum) {
            this.send(id, param, callback, count)
        }
    }

    private onPostError(id, param, callback, count, err) {
        if (count < this._retryNum) {
            this.post(id, param, callback, count);
        }
    }

    private onPostTimeout(id, param, callback, count, timeout) {
        if (count < this._retryNum) {
            this.post(id, param, callback, count)
        }
    }

    private handler(xhr:XMLHttpRequest) {
        try {
            if (xhr.readyState === 4 && 
                (xhr.status === 0 || (xhr.status >= 200 && xhr.status < 300))) {
                let rspd = JSON.parse(xhr.responseText);
                console.warn(`返回协议：msg id:${rspd.msgHead.id} ret:${rspd.code} data:${xhr.responseText}`);
                
                if(rspd.code != -1)
                {
                    //通知数据刷新
                    MsgMgr.emit("MSG_ID_"+rspd.msgHead.id+"_DATA", rspd.data);
                    let arr = this.cache[rspd.msgHead.id];
                    if(arr)
                    {
                        delete this.cache[rspd.msgHead.id];
                        for(var i=0;i<arr.length;i++)
                        {
                            arr[i](rspd);
                        }
                    } else {
                        console.warn('协议：'+rspd.msgHead.id+"未注册处理")
                    }
                    
                    //通知其他
                    //MsgMgr.emit("MSG_ID_"+rspd.msgHead.id, rspd.data);
                }else
                {
                    delete this.cache[rspd.msgHead.id];
                    Http.errorHandler && Http.errorHandler(rspd);
                }
            }
        }catch (e) {
            console.warn("http error",e)
            Http.errorHandler && Http.errorHandler(0);
        }
    }
}